package com.wuhao.shootclient.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.camera2.CameraDevice;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.util.Log;
import android.util.Size;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.wuhao.shootclient.R;
import com.wuhao.shootclient.base.BaseCameraApplication;
import com.wuhao.shootclient.bean.FaceIdentityVo;
import com.wuhao.shootclient.bean.FaceRecognitionVo;
import com.wuhao.shootclient.ui.widget.RoundBorderView;
import com.wuhao.shootclient.ui.widget.RoundTextureView;
import com.wuhao.shootclient.util.UrlHelper;
import com.wuhao.shootclient.util.YUVUtils;
import com.wuhao.shootclient.util.camera2.Camera2Helper;
import com.wuhao.shootclient.util.camera2.Camera2Listener;
import com.wuhao.shootclient.util.net.WhResponse;
import com.wuhao.shootclient.util.net.callback.JsonCallback;

import okhttp3.MediaType;
import okhttp3.RequestBody;


public class Camera2Activity extends BaseCameraApplication implements ViewTreeObserver.OnGlobalLayoutListener, Camera2Listener,View.OnClickListener{
    private static final String TAG = "CameraActivity";
    private static final int ACTION_REQUEST_PERMISSIONS = 1;
    private Camera2Helper camera2Helper;
    private RoundTextureView textureView;
    private RoundBorderView roundBorderView;
    private Button facialInformationDetection;
    private Button facialInformationRegistration;
    private Gson gsonJson;
    //识别图像byte
    private byte[] photoImage;
    private int imageWidth;
    private int imageHeight;
    //用户身份标识
    private String identityIdentification;
    //用于调整圆角大小
    private SeekBar radiusSeekBar;
    //默认打开的CAMERA
    private static final String CAMERA_ID = Camera2Helper.CAMERA_ID_FRONT;
    //需要的权限
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera2);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
        initView();
    }


    private void initView() {
        gsonJson = new Gson();
        textureView = findViewById(R.id.texture_preview);
        textureView.getViewTreeObserver().addOnGlobalLayoutListener(this);
        facialInformationDetection = findViewById(R.id.facialInformationDetection);
        facialInformationRegistration = findViewById(R.id.facialInformationRegistration);
    }

    void initCamera() {
        camera2Helper = new Camera2Helper.Builder()
                .cameraListener(this)
                .specificCameraId(CAMERA_ID)
                .context(getApplicationContext())
                .previewOn(textureView)
                .previewViewSize(new Point(textureView.getLayoutParams().width, textureView.getLayoutParams().height))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .build();
        camera2Helper.start();
    }

    @Override
    protected void onRequestPermissionResult(int requestCode, boolean isAllGranted) {
        if (requestCode == ACTION_REQUEST_PERMISSIONS) {
            if (isAllGranted) {
                initCamera();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onGlobalLayout() {
        textureView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        ViewGroup.LayoutParams layoutParams = textureView.getLayoutParams();
        int sideLength = Math.min(textureView.getWidth(), textureView.getHeight()) * 3 / 4;
        layoutParams.width = sideLength;
        layoutParams.height = sideLength;
        textureView.setLayoutParams(layoutParams);
        textureView.turnRound();
        facialInformationDetection.setOnClickListener(this);
        facialInformationRegistration.setOnClickListener(this);
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            initCamera();
        }
    }

    @Override
    protected void onPause() {
        if (camera2Helper != null) {
            camera2Helper.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (camera2Helper != null) {
            camera2Helper.start();
        }
    }


    @Override
    public void onCameraOpened(CameraDevice cameraDevice, String cameraId, final Size previewSize, final int displayOrientation, boolean isMirror) {
        Log.i(TAG, "onCameraOpened:  previewSize = " + previewSize.getWidth() + "x" + previewSize.getHeight());

        // 在相机打开时，添加右上角的view用于显示原始数据和预览数据
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 将预览控件和预览尺寸比例保持一致，避免拉伸
                {
                    ViewGroup.LayoutParams layoutParams = textureView.getLayoutParams();
                    // 横屏
                    if (displayOrientation % 180 == 0) {
                        layoutParams.height = layoutParams.width * previewSize.getHeight() / previewSize.getWidth();
                    }
                    // 竖屏
                    else {
                        layoutParams.height = layoutParams.width * previewSize.getWidth() / previewSize.getHeight();
                    }
                    textureView.setLayoutParams(layoutParams);
                }

                // 添加圆角边框视图
                roundBorderView = new RoundBorderView(Camera2Activity.this);
                ((FrameLayout) textureView.getParent()).addView(roundBorderView, textureView.getLayoutParams());
                textureView.setRadius(Math.min(textureView.getWidth(), textureView.getHeight()) / 2);
                roundBorderView.setRadius(Math.min(textureView.getWidth(), textureView.getHeight()) / 2);

                textureView.turnRound();
                roundBorderView.turnRound();
            }
        });
    }

    @Override
    public void onPreview(final byte[] y, final byte[] u, final byte[] v, final Size previewSize, int yRowStride, int uRowStride, final int vRowStride) {
    }
    @Override
    public void onCameraClosed() {
        Log.i(TAG, "onCameraClosed: ");
    }

    @Override
    public void onCameraError(Exception e) {
        e.printStackTrace();
    }

    @Override
    public void takePicture() {

    }

    @Override
    public void onPictureTaken(byte[] imageByte, int imageWidths, int imageHeights) {
        imageWidth = imageWidths;
        imageHeight = imageHeights;
        photoImage = imageByte;
    }

    @Override
    protected void onDestroy() {
        if (camera2Helper != null) {
            camera2Helper.release();
            photoImage = null;
        }
        super.onDestroy();
    }

    @SuppressLint("ResourceType")
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.facialInformationDetection:
                //导入动画效果并启动动画
                facialInformationDetection.startAnimation(AnimationUtils.loadAnimation(Camera2Activity.this, R.drawable.facial_informatio_btn_animation));
                //禁用检测和注册按钮
                btnIsEnabled(false);
                //停止预览
                camera2Helper.stopTakeRepeating();
                roundBorderView.setTipsText("正在进行人脸检测!", Color.BLUE);
                //YUV转成RGB再进行BitMap压缩处理
                Bitmap bitmap = YUVUtils.decodeRgbBitmap(YUVUtils.decodeYUV420SP(photoImage, imageWidth, imageHeight), imageWidth, imageHeight,112,112,100,0);
                //转Base64远程调用服务
                faceRecognition(YUVUtils.bitmapToBase64(bitmap));
                break;
            case R.id.facialInformationRegistration:
                //导入动画效果并启动动画
                facialInformationRegistration.startAnimation(AnimationUtils.loadAnimation(Camera2Activity.this, R.drawable.facial_informatio_btn_animation));
                if(facialInformationRegistration.getText().toString().equals("输入身份信息进行注册")){
                    //打开对话框输入信息
                    faceMesAlertDialog();
                }

                if(facialInformationRegistration.getText().toString().equals("点击按钮开始注册") && !identityIdentification.isEmpty()){
                    Log.d(TAG, identityIdentification);
                    //停止预览
                    camera2Helper.stopTakeRepeating();
                    //YUV转成RGB再进行BitMap压缩处理
                    Bitmap bitmapto = YUVUtils.decodeRgbBitmap(YUVUtils.decodeYUV420SP(photoImage, imageWidth, imageHeight), imageWidth, imageHeight,112,112,100,-90);
                    //转Base64远程调用服务
                    faceRegister(identityIdentification,YUVUtils.bitmapToBase64(bitmapto));
                }
                break;
        }
    }

    private void faceRecognition(String base64){
        OkGo.<WhResponse<FaceRecognitionVo>>post(UrlHelper.FACE + UrlHelper.FACE_RECOGNITION)
                //在body中携带参数
                .upRequestBody(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),  "{\"head\": \"" + base64 + "\"}"))
                .execute(new JsonCallback<WhResponse<FaceRecognitionVo>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<FaceRecognitionVo>> response) {
                        FaceRecognitionVo data = response.body().data;
                        if(data.getId().isEmpty()){
                            roundBorderView.setTipsText("未检测到人脸信息,请对准摄像头", Color.RED);
                            facialInformationDetection.setText("重新检测");
                            camera2Helper.startTakeRepeating();
                            //启用检测和注册按钮
                            btnIsEnabled(true);
                        }else if(data.getId().equals("未识别")){
                            //启用检测和注册按钮
                            btnIsEnabled(true);
                            facialInformationDetection.setText("重新检测");
                            camera2Helper.startTakeRepeating();
                            roundBorderView.setTipsText("没有人脸信息，请注册", Color.RED);
                        }else{
                            roundBorderView.setTipsText(data.getId()+",检测成功", Color.GREEN);
                            Intent intent = new Intent();
                            intent.putExtra("code",200);
                            intent.putExtra("name",data.getId());
                            setResult(7,intent);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<FaceRecognitionVo>> response) {
                        super.onError(response);
                        Log.d(TAG, "请求失败");
                    }
                });
        }

    private void faceRegister(String id,String base64){
        OkGo.<WhResponse<Object>>post(UrlHelper.FACE + UrlHelper.FACE_REGISTER)
                //在body中携带参数
                .upRequestBody(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),  "{\"head\": \"" + base64 + "\", \"id\": \"" + id + "\"}"))
                .execute(new JsonCallback<WhResponse<Object>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<Object>> response) {
                        if(response.body().code==1){
                            roundBorderView.setTipsText("注册成功！请人脸检测", Color.GREEN);
                            camera2Helper.startTakeRepeating();
                        }
                        if(response.body().code==0){
                            roundBorderView.setTipsText("注册失败！"+response.body().msg, Color.RED);
                            camera2Helper.startTakeRepeating();
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<Object>> response) {
                        super.onError(response);
                        Log.d(TAG, "请求失败");
                    }
                });
    }


    private void queryInformation(String id,AlertDialog.Builder builder, EditText idtext){
        OkGo.<WhResponse<FaceIdentityVo>>get(UrlHelper.FACE + UrlHelper.QUERY_FACE_REGISTER)
                .params("id",id)
                .execute(new JsonCallback<WhResponse<FaceIdentityVo>>() {
                    @Override
                    public void onSuccess(Response<WhResponse<FaceIdentityVo>> response) {
                        if(response.body().code==0 && response.body().msg.equals("用户不存在！")){
                            identityIdentification = id;
                            facialInformationRegistration.setText("点击按钮开始注册");
                            Toast.makeText(Camera2Activity.this,"用户名设置成功..",Toast.LENGTH_SHORT).show();
                            roundBorderView.setTipsText("正对摄像机进行脸部信息注册..", Color.BLUE);
                        }else{
                            Toast.makeText(Camera2Activity.this,"用户名已存在请重新输入！",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<WhResponse<FaceIdentityVo>> response) {
                        super.onError(response);
                        Log.d(TAG, "请求失败");
                    }
                });
    }


        private void faceMesAlertDialog(){
            // 创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("人脸信息注册");
            View faceDataView = getLayoutInflater().inflate(R.layout.dialog_faceregister, null);
            builder.setView(faceDataView);
            EditText idtext = faceDataView.findViewById(R.id.identity_identification);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if(!idtext.getText().toString().trim().isEmpty()){
                        queryInformation(idtext.getText().toString().trim(),builder,idtext);
                    }else{
                        Toast.makeText(Camera2Activity.this,"用户名不能为空,请重新输入！",Toast.LENGTH_SHORT).show();
                        idtext.setError("不能为空,请重新输入");
                    }
                }
            });
            //取消按钮
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 处理取消按钮点击事件
                    dialog.dismiss();
                }
            });

            // 显示对话框
            builder.show();
        }


        private void btnIsEnabled(Boolean isenabled){
            facialInformationDetection.setEnabled(isenabled);
            facialInformationRegistration.setEnabled(isenabled);
        }
    }